<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <title>WebSocket</title>
</head>

<body>
  <p id="output"></p>
  <p>
	<input type="text" id="answer">
	<button id="submit">submit</button>
  </p>

  <script>
    var loc = window.location;
    var uri = 'ws:';

    if (loc.protocol === 'https:') {
      uri = 'wss:';
    }
    uri += '//' + loc.host;
    uri += loc.pathname + 'ws';
	console.log(uri);
	
	uri = 'ws://127.0.0.1:1323/ws';
    ws = new WebSocket(uri)
	
	var submit = document.getElementById('submit');
	var millisecond=0;
	var int;
	submit.onclick = function(){
		var answer = document.getElementById('answer').value;
		document.getElementById('answer').value = ""
		var message = new Object();
		var data = new Object();
		data.answer = answer;
		data.question = "";
		// data.elapsed_time = millisecond;
		
		message.category = "send_answer";
		message.message = "";
		message.data = data;
		ws.send(JSON.stringify(message))
	}

    ws.onopen = function() {
		var out = document.getElementById('output');
		
		out.innerHTML += "wait for other player<br>"
    }

    ws.onmessage = function(evt) {
      var out = document.getElementById('output');
	  var message = JSON.parse(evt.data)
	  switch (message.category) {
		case "match_complete":
			out.innerHTML += "match_complete<br>"
			message.category = "get_question";
			message.message = "";
			message.data.question = "";
			message.data.answer = "";
			// message.data.elapsed_time = 0;
			ws.send(JSON.stringify(message))
			break;
		case "send_question":
			out.innerHTML += "question is :" + message.data.question + "<br>";
			break;
		case "send_result":
			out.innerHTML += message.message + "<br>";
			message.category = "get_question";
			message.message = "";
			message.data.question = "";
			message.data.answer = "";
			// message.data.elapsed_time = 0;
			ws.send(JSON.stringify(message))
			break;
		case "send_notify":
			out.innerHTML += message.message + "<br>";
			break;
	  }
	  console.log(message.category)
      //out.innerHTML += evt.data + '<br>';
    }
  </script>
</body>

</html>